package com.thx.common.struts2;

import com.opensymphony.xwork2.ActionSupport;
import com.thx.common.web.ActionResult;

import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Action 基础类.
 *
 * @author 贾红磊
 */
public class BaseAction extends ActionSupport {

  private static final long serialVersionUID = -46111079141876527L;

  protected final Logger logger = LoggerFactory.getLogger(getClass());

  protected static final String AUDIT = "audit";
  protected static final String JSON = "json";
  public static final String RELOAD = "reload"; // 重定向的返回字符串
  public static final String REDIRECT = "redirect"; // 重定向，@Result
  public static final String REDIRECT_ACTION = "redirectAction"; // Action之间重定向，@Result
  // type属性对应的值

  protected String message;// 操作成功时，页面的提示信息

  protected String sessionId;

  protected ActionResult result;// 用于通过json返回处理结果时

  /**
   * 取得HttpSession函数.
   */
  public static HttpSession getSession() {
    return ServletActionContext.getRequest().getSession();
  }

  /**
   * 取得HttpRequest函数.
   */
  public static HttpServletRequest getRequest() {
    return ServletActionContext.getRequest();
  }

  /**
   * 取得HttpResponse函数.
   */
  public static HttpServletResponse getResponse() {
    return ServletActionContext.getResponse();
  }

  /**
   * 返回JSON调用的方法.
   */
  protected void writeJson(String json) throws IOException {
    HttpServletResponse response = ServletActionContext.getResponse();
    // response.setContentType("application/json;charset=UTF-8");
    response.setContentType("text/html;charset=UTF-8");
    response.setCharacterEncoding("utf-8");
    response.setHeader("Charset", "utf-8");
    response.setHeader("Cache-Control", "no-cache");
    response.getWriter().print(json);

  }

  public String getMessage() {
    return message;
  }

  public void setMessage(String message) {
    this.message = message;
  }

  public String getSessionId() {
    return sessionId;
  }

  public void setSessionId(String sessionId) {
    this.sessionId = sessionId;
  }

  public ActionResult getResult() {
    return result;
  }

  public void setResult(ActionResult result) {
    this.result = result;
  }

  public void setResult(String code, String desc) {
    this.result = new ActionResult(code, desc);
  }
  
  public void setResult(String code, String desc,Map<String,Object> data) {
    this.result = new ActionResult(code, desc,data);
  }
}
